const app = getApp();
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
  key: '37BBZ-IASRP-7VZDT-V6FJE-USUFE-OVFGR' // 必填
});
Page({
  data: {
    showAD: true,
    show_webview: false,
    show_adv: false,
    isBottom: 0,
    cates: [
      { title: '资讯', icon: 'https://www.58zltc.com/Public/quan/quan_icon1.png', url: 'news/news' },
      // { title: '视频', icon: 'https://www.58zltc.com/Public/quan/quan_icon2.png', url: 'video/video' },
      // { title: '话题', icon: 'https://www.58zltc.com/Public/quan/quan_icon3.png', url: 'topic/list' },
      { title: '附近', icon: 'https://www.58zltc.com/Public/quan/quan_icon4.png', url: 'member/fujin' },
      { title: '达人榜', icon: 'https://www.58zltc.com/Public/quan/quan_icon5.png', url: 'member/daren' },
      // { title: '问答', icon: 'https://www.58zltc.com/Public/quan/quan_icon6.png', url: 'question/question' },
      // { title: '交友', icon: 'https://www.58zltc.com/Public/quan/quan_icon7.png', url: 'member/friend' },
      // { title: '圈子', icon: 'https://www.58zltc.com/Public/quan/quan_icon8.png', url: 'quan/quan' },
    ],
    flashList:[
     "https://www.58zltc.com/Uploads/2018-05-03/5aeb16a2b3d4a.jpg" ,
     "https://www.58zltc.com/Uploads/2018-05-03/5aeb169bcf06a.jpg",
     "https://www.58zltc.com/Uploads/2018-05-03/5aeb169370cfc.jpg",
    ],
    tabs: ['最新动态', '好友动态'],
    tabIndex: 0,
    pian:0,
    list: [],
    topic_list: [],
    is_gift: false,
    pageNum: 0,
    focus:false,
    reply_text: '填写评论……',
    reply_nickname: '',
    reply_openid: '',
    reply_id:'',
    sendInput:'',
    count:'',
    fenxiangzhuan: {
      show: false,
      width: '118rpx;',
      height: '100rpx;',
      bottom: '212rpx;',
      top: '16rpx'
    }
  },
  chat:function(e){
    //同城卡
    app.ihttpGet('https://www.58zltc.com/api.php/Shop/haveTCCard/openid/' + app.globalData.openid, function (res) {
      if (res.data.have_car == 0) {
        wx.showModal({
          title: '提示',
          content: '还没有开通同城卡，是否开通？',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/shop/tccar/tccar',
              })
            }
          }
        })
      }else{
        wx.navigateTo({
          url: '/pages/quan/member/chat',
        })
      }
    });

  },
  setTab: function (e) {
    // console.log(e);
    var index = e.currentTarget.dataset.index;
    this.setData({
      tabIndex: index,
      pageNum:0
    })
    var that = this;
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
    wx.request({
      url: 'https://www.58zltc.com/api.php/Quan/index?openid=' + app.globalData.openid + '&token=' + extConfig.appid + '&pageNum=' + that.data.pageNum + '&tabindex=' + index,
      success: res => {
        var to = [];
       // console.log(res)
        res.data.forEach(function (value, key) {
          var position = { latitude: value.latitude, longitude: value.longitude };
          to.push();
        })
        if (to) {
          qqmapsdk.calculateDistance({
            to: to,
            success: function (res) {
              this.setData({
                distance: res.result.distance
              })
            }, fail: function (a) {
             // console.log(a);
            }
          });
        }
        that.setData({
          pageNum: that.data.pageNum + 1,
          list: res.data,
        })
       // console.log(that.data)
        wx.hideLoading()
      }
    })
  },
  onShow() {
    this.setData({
      show_webview: false
    })
    let that = this;
    if (app.globalData.add){
      that.setData({
        pageNum:0
      })
    }
    if(that.data.topic_list.length >0){
      that.onLoad({showAD: 'no'});
    }
  },
  onLoad: function (options) {
    let that = this;
    if (options.showAD == 'no') {
      that.setData({
        showAD: false
      })
    }
    app.ihttpGet("https://www.58zltc.com/api.php/Index/pian", function (res) {
      if (res.data.pian == 1) {
        that.setData({
          pian:1
        })
      }
    })

    wx.showLoading({
      title: '加载中…',
    })
    if (!app.globalData.userInfo) {
      //app.getOpenid();
      app.getUserInfo();
    }
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
    app.ihttpGet('https://www.58zltc.com/api.php/Quan/topicList',function(res){
      that.setData({
        topic_list: res.data
      })
    });
    app.ihttpGet('https://www.58zltc.com/api.php/Quan/giftList', function (res) {
      //console.log(res)
      that.setData({
        gift_list: res.data
      })
    });
    app.ihttpGet('https://www.58zltc.com/api.php/Quan/banner', function (res) {
      that.setData({
        banner: res.data
      })
    });
    var post_data = { openid: app.globalData.openid };
    wx.request({
      url: "https://www.58zltc.com/api.php/Quan/unReadNum?token=" + extConfig.appid,
      method: 'POST',
      data: post_data,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        that.setData({
          count: res.data
        })
      }
    });
    wx.request({
      url: 'https://www.58zltc.com/api.php/Quan/index?openid=' + app.globalData.openid + '&token=' + extConfig.appid + '&pageNum=' + that.data.pageNum +'&tabindex=0',
      success: res => {
        var to = [];
       // console.log(res)
        res.data.forEach(function(value, key){
          var position = { latitude: value.latitude, longitude: value.longitude}; 
          to.push();
        })
        if(to){
          qqmapsdk.calculateDistance({
            to: to,
            success: function (res) {
              that.setData({
                distance: res.result.distance
              })
            }, fail: function (a) {
            //  console.log(a);
            }
          });
        }
        that.setData({
          pageNum:that.data.pageNum +1,
          list: res.data,
        })
       // console.log(that.data)
        wx.hideLoading()
      }
    })
    // 广告
    if (that.data.showAD) {
      wx.request({
        url: 'https://www.58zltc.com/api.php/Index/getAdvShop?token=' + extConfig.appid + '&pos=3',
        success: res => {
          if (res.data) {
            that.setData({
              shop_advInfo: res.data,
              show_adv: true
            })
          }
        }
      })
    }
  },
  goDetail: function(e){
    var id = e.currentTarget.dataset.id;
   console.log(e.currentTarget.dataset.video);
    if (e.currentTarget.dataset.video){
      var url = '/pages/quan/video/video?id=' + id;
    }else{
      var url = '/pages/quan/detail?id=' + id;
    }
    wx.navigateTo({
      url: url,
    })
  },
  jump:function(e){
    var id = e.currentTarget.dataset.id;
    this.setData({
      focus: true,
      reply_id: id,
      reply_text: ''
    })
  },
  comment: function (e) {
    var id = e.currentTarget.dataset.id;
    var reply_nickname = e.currentTarget.dataset.nickname;
    var reply_openid = e.currentTarget.dataset.openid;
    var reply_text = "回复" + reply_nickname + ":";
    var openid = app.globalData.openid;
    if (reply_openid != openid) {
      
      this.setData({
        focus: true,
        reply_text: reply_text,
        reply_openid: reply_openid,
        reply_nickname: reply_nickname,
        reply_id:id
      })
    }

  },
  sendInputBind: function (e) {
    this.setData({
      sendInput: e.detail.value
    })
  },
  setReplyText: function (e) {
    this.setData({
      focus:false,
      reply_id: '',
    })
  },
  reply: function (e) {
   
    let that = this;
    var value = that.data.sendInput;
    if (!value) {
      return false;
    }
    console.log(that.data.repl);
    var post_data = [];
    post_data.content = value;
    post_data.openid = app.globalData.openid;
    post_data.id = that.data.reply_id;
    post_data.reply_openid = that.data.reply_openid;
    post_data.reply_nickname = that.data.reply_nickname;
    post_data.reply_part = 'quan';
    app.ihttpPost("https://www.58zltc.com/api.php/Quan/reply", post_data, function (res) {
      if (res.data.err_code === 400) {
        wx.showToast({
          title: res.data.err_msg,
          icon:'none'
        })
      } else if (res.data.err_code === 0) {
        wx.showToast({
          title: res.data.err_msg,
          icon: 'success'
        })
        that.setData({
          focus:false,
          sendInput:''
        });
        setTimeout(function () {
          that.onLoad({ showAD: 'no' });
        }, 1000)
      }
    })
  },
  goMember: function(e){
    var openid = e.currentTarget.dataset.openid;
    var url = '/pages/quan/member/member?openid=' + openid;
    wx.navigateTo({
      url: url,
    })
  },
  gift: function(e){
    var id = e.currentTarget.dataset.id;
    this.setData({
      is_gift: true,
      gift_id: id
    })
  },
  hiddenGift: function(e){
    this.setData({
      is_gift: false
    })
  },
  setGift: function(e){
    var idx = e.currentTarget.dataset.idx;
    let that = this;
    var gift_list = that.data.gift_list;
    gift_list.forEach(function(value, key){
      gift_list[key].active = key == idx?true:false;
    })
    this.setData({
      gift_list: gift_list,
      active_gift: gift_list[idx]
    })
  },
  payGift: function (e) {
    let that = this;
    var data = this.data;
    var post_data = {};

    data.list.forEach(function(value, idx){
      if(value.id == data.gift_id){
        post_data.to = value.follow_openid;
      }
    })
    post_data.type = 'quan';
    post_data.from = app.globalData.openid;
    post_data.id = data.gift_id;
    post_data.gift_id = data.active_gift.id;

    app.ihttpPost('https://www.58zltc.com/api.php/Quan/payGift', post_data, function (res) {
      if (res.data.err_code == 400) {
        wx.showToast({
          title: res.data.err_msg,
        })
      } else {
        var data = res.data;
        wx.requestPayment({
          'appId': data.appId,
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': 'MD5',
          'paySign': data.paySign,
          'success': res => {
            if (res.errMsg == 'requestPayment:ok') {
              wx.showToast({
                title: '赠送成功！',
              })
            }
          }
        })
        that.reBg();
      }
    })
  },
  zan: function (e) {
    // wx.showLoading({
    //   title: '加载中…',
    // })
    var id = e.currentTarget.dataset.id;
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
    var list = this.data.list;
    var that = this;
    wx.request({
      url: 'https://www.58zltc.com/api.php/Quan/zan?openid=' + app.globalData.openid +'&id=' + id + '&token=' + extConfig.appid,
      success: res => {
        if (res.data.err_code === 0) {
          list.forEach(function (vo, idx) {
            if (vo.id == id) {
              if(res.data.err_msg == '-1'){
                list[idx].zan_num = parseInt(list[idx].zan_num) - 1;
                list[idx].is_zan = false;
              }else{
                list[idx].zan_num = parseInt(list[idx].zan_num) + 1;
                list[idx].is_zan = true;
              }
            }
          })
          that.setData({
            list: list
          })
          //wx.hideLoading()
        } else {
          wx.showToast({
            title: res.data.err_msg
          })
        }
      }
    })
  },

  showImgs: function(e){
    const pics = e.currentTarget.dataset.pics;
    const first_pics = e.currentTarget.dataset.image;
    wx.previewImage({
      urls: pics,
      current:first_pics
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    app.confirmCommission()
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad({ showAD: 'no' });
    setTimeout(function () {
      wx.stopPullDownRefresh()
      wx.showToast({
        title: '已刷新',
      })
    }, 2000)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this;
    return {
      title: '同城圈',
      path: '/pages/quan/quan' + '?fenxiang=' + app.globalData.openid + '&fWid=' + app.globalData.wid,
      success: function (res) {
        var a = that.data.fenxiangzhuan
        a.show = false
        that.setData({
          fenxiangzhuan: a
        })
        // 转发成功
        wx.showToast({
          title: '转发成功！',
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  onReachBottom: function () {
    wx.showLoading({
      title: '加载中…',
    })
    var that = this;
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
    wx.request({
      url: 'https://www.58zltc.com/api.php/Quan/index?t=bottom&openid=' + app.globalData.openid + '&token=' + extConfig.appid + '&pageNum=' + that.data.pageNum +"&tabindex=" + that.data.tabIndex,
      success: res => {
        if (that.data.list.length == res.data.length) {
          that.setData({
            isBottom: 1
          })
        }
        var newPage = that.data.pageNum + 1;
       // console.log(newPage)
        that.setData({
          pageNum: newPage
        })
        that.setData({
          list: res.data
        })
        wx.hideLoading()
      }
    })
  },
  changeFXZ: function () {
    var that = this;
    var a = that.data.fenxiangzhuan
    a.show ? a.show = false : a.show = true
    that.setData({
      fenxiangzhuan: a
    })
  },
  jumpWeb: function (e) {
    console.log(e.currentTarget.dataset.type)
    let that = this
    var type_num = e.currentTarget.dataset.type
    var show_web = false
    if (type_num == 2) {
      show_web = true
    }
    this.setData({
      show_webview: show_web,
      show_adv: false
    })
  },
  onTabItemTap(item) {
    console.log(item)
    if (item.index == 3) {
      this.setData({
        show_webview: false
      })
    }
  },
  closeAdv: function () {
    this.setData({
      show_adv: false
    })
  }
})